package com.bruce.codeFactory.Thread.designMode.TwoPhase;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author luotuan
 * @Description
 * @create 2019-03-11 22:32
 **/
public class AppServer extends Thread {
    private final int port;
    private static final int DEFAULT_PORT = 15441;
    private volatile boolean start = true;
    private List<ClientHandler> clientHandlers = new ArrayList<>();
    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    private ServerSocket serverSocket;

    public AppServer() {
        this(DEFAULT_PORT);
    }

    public AppServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("Starting the server,port--->" + port);
            while (start) {
                Socket socket = serverSocket.accept();
                ClientHandler handler = new ClientHandler(socket);
                executor.submit(handler);
                clientHandlers.add(handler);
            }
        } catch (IOException e) {
            System.out.println("========="+e.getMessage());
        } finally {
            System.out.println("closing........");
            dispose();
        }
    }

    private void dispose() {
        this.clientHandlers.stream().forEach(ClientHandler::stop);
        this.executor.shutdown();
    }

    public void shutDown() {
        this.start = false;
        this.interrupt();
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
